# coding=utf-8
from django.http import JsonResponse
from django.shortcuts import render
from fabric.api import local, abort, settings, env, cd, run
from fabric.colors import *
from fabric.contrib.console import confirm
import fabric

host_d = {
    'syl_test': 'python@10.211.55.15',
}
env.hosts = [
    'python@10.211.55.15',
]
env.passwords = {
    'python@10.211.55.15': 'jiyun123#@!',
}
env.host_string = ""
env.key_filename = ''
env.port = '22'

env['auto_type'] = {
    'password': '',
}


def setEnv(hostString):
    env.host_string = host_d.get(hostString)
    env.password = env.passwords.get(env.host_string)


def index(request):
    return render(request, 'index.html', locals())


def pwd():
    pwd_result = local("pwd", capture=True)
    print(pwd_result)


def hg_pull_u(request):
    setEnv('syl_test')  # 设置要操作的主机
    with cd('~/Desktop/shiyanlou_project'):
        result = run('git pull')
    msg = result
    return render(request, 'result.html', locals())


def reload_gunicorn(request):
    with settings():
        # pwd_result = run("kill -HUP `ps aux|grep gunicorn|awk 'NR==1{print$2}'`")  # 重启gunicorn
        pwd_result = run("kill -HUP `lsof -i:8015 | awk 'NR==2{print $2}'`")  # 重启8015端口的进程
        print(pwd_result)
    msg = 'ok'
    return render(request, 'result.html', locals())


def get_git_status():
    git_status_result = local("git status", capture=True)
    if "无文件要提交，干净的工作区" not in git_status_result:
        print(red("****当前分支还有文件没有提交"))
        print(git_status_result)
        abort("****已经终止")


def local_unit_test():
    with settings(warn_only=True):
        test_result = local("python manage.py test")
        if test_result.failed:
            print(test_result)
            if not confirm(red("****单元测试失败，是否继续？")):
                abort("****已经终止")


def server_unit_test():
    with settings(warn_only=True):
        test_result = run("python manage.py test")
        if test_result.failed:
            print(test_result)
            if not confirm(red("****单元测试失败，是否继续？")):
                abort("****已经终止")


def upload_code():
    local("git push origin dev")
    print(green("****代码上传成功"))


def deploy_at_server():
    print(green("****ssh到服务器进行下列操作"))
    with cd("/var/www/××××××"):
        # print(run("pwd"))
        print(green("****将在远程仓库下载代码"))
        run("git checkout dev")
        get_git_status()
        run("git pull origin dev")
        print(green("****将在服务器上运行单元测试"))
        server_unit_test()
        run("service apache2 restart", pty=False)
        print(green("****重启apache2成功"))
        print(green("********代码部署成功********"))


def deploy():
    get_git_status()
    local("git checkout dev", capture=False)
    print(green("****切换到dev分支"))
    get_git_status()
    print(green("****将开始运行单元测试"))
    local_unit_test()
    print(green("****单元测试完成，开始上传代码"))
    upload_code()
    deploy_at_server()


if __name__ == '__main__':
    pass
    # pwd_r()
    hg_pull_u()
